//
//  FavAllViewController.m
//  Rail
//
//  Created by hychen on 2018/2/27.
//  Copyright © 2018年 Hychen. All rights reserved.
//

#import "FavAllViewController.h"
#import "SelectFactoryFoldCellModel.h"
#import "AllFavGroupTableViewCell.h"
#import "AllFavTableViewCell.h"
#import "TextFieldAlertView.h"
#import "BMAlertView.h"
#import "SelectGroupController.h"
#import "LineDetailViewController.h"
#import "FactoryDetailViewController.h"
#import "JumpTool.h"

@interface FavAllViewController () <UIAlertViewDelegate>
@property (nonatomic, strong) AllFavListModel *model;
@property (nonatomic, weak) BMAlertView *alertView;
@property (nonatomic, strong) NSIndexPath *deleteIndexPath;
@end

@implementation FavAllViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)refreshData {
    BMWeakSelf
    [HttpRequest loadFavAllListDataSuccess:^(NSArray *object) {
        weakSelf.dataArray = object.mutableCopy;
        [weakSelf setupTableViewData];
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView reloadData];
    } failure:^(NSString *code, NSString *msg) {
        [weakSelf.tableView.mj_header endRefreshing];
        Show_Msg_Error(msg)
    }];
}

- (void)setupTableViewData {
    NSMutableArray *dataArray = [NSMutableArray array];
    for (int i = 0; i < self.dataArray.count; ++i) {
        //Level-0
        SelectFactoryFoldCellModel *secFoldModel = [SelectFactoryFoldCellModel new];
        secFoldModel.level = @"0";
        AllFavListModel *listModel = [self.dataArray objectAtIndexSafe:i];
        secFoldModel.obj = listModel;
        secFoldModel.belowCount = 0;
        NSMutableArray *subArray = [NSMutableArray array];
        for (int j = 0; j < listModel.fav_list.count; ++j) {
            //Level-1
            AllFavModel *favModel = [listModel.fav_list objectAtIndexSafe:j];
            SelectFactoryFoldCellModel *rowFoldModel = [SelectFactoryFoldCellModel new];
            rowFoldModel.level = @"1";
            rowFoldModel.obj = favModel;
            rowFoldModel.belowCount = 0;
            [subArray addObject:rowFoldModel];
        }
        secFoldModel.submodels = subArray;
        [dataArray addObject:secFoldModel];
    }
    self.dataArray = dataArray;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SelectFactoryFoldCellModel *foldModel = [self.dataArray objectAtIndex:indexPath.row];
    if ([foldModel.obj isKindOfClass:[AllFavListModel class]]) {
        AllFavGroupTableViewCell *cell = [AllFavGroupTableViewCell cellWithTableView:tableView class:[AllFavGroupTableViewCell class]];
        cell.model = (AllFavListModel *)foldModel.obj;
        cell.isExpand = foldModel.belowCount == 0;
        if ([cell.model.dirid isEqualToString:@"0"] || [cell.model.dirid isEqualToString:@""]) {
            cell.showAddButton = YES;
            BMWeakSelf
            [cell setBlockClickAddButton:^{
                
                TextFieldAlertView *textField = [TextFieldAlertView alertView];
                CGRect frame = textField.frame;
                CGFloat textFieldX = (SCREEN_WIDTH-frame.size.width)*0.5;
                CGFloat textFieldY = (SCREEN_HEIGHT-frame.size.height)*0.2;
                frame.size.height = ResizeH(200);
                frame.origin.x = textFieldX;
                frame.origin.y = textFieldY;
                textField.frame = frame;
                textField.title = @"新增栏目";
                weakSelf.alertView = [BMAlertView showCustomView:textField isCenter:NO configuration:^(BMAlertView *tempView) {
                    [weakSelf.view endEditing:YES];
                    tempView.isShowOverlay = YES;
                    tempView.isTouchEdgeHide = YES;
                }];
                BMWeakSelf
                [textField setBlockClickSubmit:^(NSString *text) {
                    [weakSelf.view endEditing:YES];
                    if ([text isEqualToString:@""]) {
                        Show_Msg_Error(@"栏目名称不能为空")
                        return;
                    }
                    [weakSelf addGroupWithName:text];
                    [weakSelf.alertView dismissAlert];
                }];
                
            }];
        }
        else {
            cell.showAddButton = NO;
        }
        return cell;
    }
    else if ([foldModel.obj isKindOfClass:[AllFavModel class]]) {
        AllFavTableViewCell *cell = [AllFavTableViewCell cellWithTableView:tableView class:[AllFavTableViewCell class]];
        cell.model = (AllFavModel *)foldModel.obj;
        return cell;
    }
    return [UITableViewCell new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44.f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    SelectFactoryFoldCellModel *didSelectModel = [self.dataArray objectAtIndex:indexPath.row];
    
    if ([didSelectModel.obj isKindOfClass:[AllFavListModel class]]) {
        
        [tableView beginUpdates];
        if (didSelectModel.belowCount == 0) {
            //展开
            NSArray *submodels = [didSelectModel open];
            NSIndexSet *indexes = [NSIndexSet indexSetWithIndexesInRange:((NSRange){indexPath.row + 1,submodels.count})];
            [self.dataArray insertObjects:submodels atIndexes:indexes];
            
            //Rows
            NSMutableArray *indexPaths = [NSMutableArray new];
            for (int i = 0; i < submodels.count; i++) {
                NSIndexPath *insertIndexPath = [NSIndexPath indexPathForRow:(indexPath.row + 1 + i) inSection:indexPath.section];
                [indexPaths addObject:insertIndexPath];
            }
            [tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
        }
        else {
            //收缩
            NSArray *submodels = [self.dataArray subarrayWithRange:((NSRange){indexPath.row + 1,didSelectModel.belowCount})];
            [didSelectModel closeWithSubmodels:submodels];
            [self.dataArray removeObjectsInArray:submodels];
            
            //Rows
            NSMutableArray *indexPaths = [NSMutableArray new];
            for (int i = 0; i < submodels.count; i++) {
                NSIndexPath *insertIndexPath = [NSIndexPath indexPathForRow:(indexPath.row + 1 + i) inSection:indexPath.section];
                [indexPaths addObject:insertIndexPath];
            }
            [tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
        }
        [tableView endUpdates];
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }
    else if ([didSelectModel.obj isKindOfClass:[AllFavModel class]]) {
        AllFavModel *favModel = (AllFavModel *)didSelectModel.obj;
        switch (favModel.fav_type) {
            case FavTypeWorkArea:
            {
                //点击工区
                [self gotoFactoryDetailWithFactoryId:favModel.areaid factoryName:favModel.area_name];
            }
                break;
            case FavTypeDevice:
            {
                //点击设备
                [self gotoDeviceDetail:favModel];
            }
                break;
            case FavTypeLine:
            {
                //点击线路
                [self gotoLineDetailWithLineId:favModel.lineid];
            }
                break;
            default:
                break;
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
    SelectFactoryFoldCellModel *didSelectModel = [self.dataArray objectAtIndex:indexPath.row];
    return [didSelectModel.level integerValue];
}

#pragma mark - tableView自带的编辑功能
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
    }
}
// 选择编辑的样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}
// 修改delete的文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}

// 设置显示多个按钮
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.row == 0) {
        //第一个为默认分栏 不可编辑
        return @[];
    }
    
    SelectFactoryFoldCellModel *didSelectModel = [self.dataArray objectAtIndex:indexPath.row];
    
    BMWeakSelf
    UITableViewRowAction * deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [[[UIAlertView alloc] initWithTitle:@"是否删除栏目" message:nil delegate:weakSelf cancelButtonTitle:@"取消" otherButtonTitles:@"删除", nil] show];
        weakSelf.deleteIndexPath = indexPath;
    }];
    deleteRowAction.backgroundColor = [UIColor redColor];
    
    if ([didSelectModel.obj isKindOfClass:[AllFavListModel class]]) {
        //修改
        UITableViewRowAction * topRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"修改" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
            SelectFactoryFoldCellModel *model = [self.dataArray objectAtIndex:indexPath.row];
            [weakSelf renameGroupWithFoldModel:model.obj indexPath:indexPath];
        }];
        topRowAction.backgroundColor = Color_RGB(38, 192, 223);
        
        return @[deleteRowAction,topRowAction];
    }
    else if ([didSelectModel.obj isKindOfClass:[AllFavModel class]]) {
        //移至
        UITableViewRowAction * topRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"移至" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
            SelectFactoryFoldCellModel *model = [self.dataArray objectAtIndex:indexPath.row];
            
            SelectGroupController *vc = [SelectGroupController new];
            vc.favId = ((AllFavModel *)model.obj).favid;
            if (![vc.favId objectIsNotEmpty]) {
                return;
            }
            [vc setBlockSuccessCallBack:^{
                //刷新获取最新栏目数据
                [weakSelf.tableView.mj_header beginRefreshing];
            }];
            [weakSelf.navigationController pushViewController:vc animated:YES];

        }];
        topRowAction.backgroundColor = Color_RGB(38, 192, 223);
        
        return @[deleteRowAction,topRowAction];
    }
    
    return @[];
}

#pragma mark - 操作
//删除Row
- (void)deleteRowWithFoldModel:(SelectFactoryFoldCellModel *)model indexPath:(NSIndexPath *)indexPath {
    if ([model.obj isKindOfClass:[AllFavListModel class]]) {
        [self deleteGroupWithModel:model.obj indexPath:indexPath];
    }
    else if ([model.obj isKindOfClass:[AllFavModel class]]) {
        [self cancelFavWithModel:model.obj indexPath:indexPath];
    }
}

//修改栏目名称
- (void)renameGroupWithFoldModel:(AllFavListModel *)model indexPath:(NSIndexPath *)indexPath {
    //弹窗修改
    TextFieldAlertView *textField = [TextFieldAlertView alertView];
    
    CGRect frame = textField.frame;
    CGFloat textFieldX = (SCREEN_WIDTH-frame.size.width)*0.5;
    CGFloat textFieldY = (SCREEN_HEIGHT-frame.size.height)*0.2;
    frame.size.height = ResizeH(200);
    frame.origin.x = textFieldX;
    frame.origin.y = textFieldY;
    textField.frame = frame;
    textField.title = @"修改栏目名称";
    self.alertView = [BMAlertView showCustomView:textField isCenter:NO configuration:^(BMAlertView *tempView) {
         tempView.isShowOverlay = YES;
         tempView.isTouchEdgeHide = YES;
    }];
    BMWeakSelf
    [textField setBlockClickSubmit:^(NSString *text) {
        if ([text isEqualToString:@""]) {
            return;
        }
        [weakSelf requestRenameData:text groupId:model.dirid indexPath:indexPath];
        [weakSelf.alertView dismissAlert];
    }];
}

//删除收藏栏目
- (void)deleteGroupWithModel:(AllFavListModel *)model indexPath:(NSIndexPath *)indexPath {
    Show_ActionEnabled
    Show_NoMsg
    BMWeakSelf
    [HttpRequest deleteFavGroupWithGroupId:model.dirid success:^(id object) {
        [weakSelf.dataArray removeObjectAtIndex:indexPath.row];
        [weakSelf.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        Dismiss_NoMsg
        Show_ActionDisabled
    } failure:^(NSString *code, NSString *msg) {
        Show_Msg_Error(msg)
        Show_ActionDisabled
    }];
}

//增加收藏栏目
- (void)addGroupWithName:(NSString *)groupName {
    Show_ActionEnabled
    Show_NoMsg
    BMWeakSelf
    [HttpRequest addFavGroupWithGroupName:groupName success:^(id object) {
        [weakSelf.tableView.mj_header beginRefreshing];
        Dismiss_NoMsg
        Show_ActionDisabled
    } failure:^(NSString *code, NSString *msg) {
        Show_Msg_Error(msg)
        Show_ActionDisabled
    }];
}

//取消收藏
- (void)cancelFavWithModel:(AllFavModel *)model indexPath:(NSIndexPath *)indexPath {
    Show_ActionEnabled
    Show_NoMsg
    BMWeakSelf
    [HttpRequest cancelFavWithFavId:model.favid success:^(id object) {
        [weakSelf.dataArray removeObjectAtIndex:indexPath.row];
        [weakSelf.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        Dismiss_NoMsg
        Show_ActionDisabled
    } failure:^(NSString *code, NSString *msg) {
        Show_Msg_Error(msg)
        Show_ActionDisabled
    }];
}

#pragma mark -
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1 && self.deleteIndexPath) {
        SelectFactoryFoldCellModel *model = [self.dataArray objectAtIndex:self.deleteIndexPath.row];
        //删除
        [self deleteRowWithFoldModel:model indexPath:self.deleteIndexPath];
    }
}

#pragma mark - 跳转
//线路详情
- (void)gotoLineDetailWithLineId:(NSString *)lineId {
    LineDetailViewController *vc = [LineDetailViewController new];
    vc.lineId = lineId;
    [self.navigationController pushViewController:vc animated:YES];
}

//工区详情
- (void)gotoFactoryDetailWithFactoryId:(NSString *)factoryId factoryName:(NSString *)factoryName{
    //工区详情
    FactoryDetailViewController *vc = [FactoryDetailViewController new];
    vc.areaid = factoryId;
    vc.navTitle = factoryName;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)gotoDeviceDetail:(AllFavModel *)model {
//    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    Show_Msg(@"请稍等...")
    BMWeakSelf
    [HttpRequest loadDeviceVideoDetailDataWithDeviceId:model.deviceid success:^(SelectVideoDeviceModel *object) {
//        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
        Dismiss_NoMsg
        if ([object isKindOfClass:[SelectVideoDeviceModel class]]) {
            [JumpTool gotoWatchVideoVc:weakSelf deviceModel:object];
        }
    } failure:^(NSString *code, NSString *msg) {
//        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
        Show_SV_Error_Msg(msg)
    }];
}

#pragma mark - 网络请求
- (void)requestRenameData:(NSString *)newName groupId:(NSString *)groupId indexPath:(NSIndexPath *)indexPath {
    Show_NoMsg
    BMWeakSelf
    [HttpRequest updateFavGroupWithGroupName:newName groupId:groupId success:^(id object) {
        Show_Msg_Success(@"修改成功")
        SelectFactoryFoldCellModel *cellModel = [weakSelf.dataArray objectAtIndexSafe:indexPath.row];
        if ([cellModel isKindOfClass:[SelectFactoryFoldCellModel class]] && [cellModel.obj isKindOfClass:[AllFavListModel class]]) {
            ((AllFavListModel *)cellModel.obj).dir_name = newName;
            [weakSelf.tableView reloadData];
        }
        else {
            [weakSelf.tableView.mj_header beginRefreshing];
        }
    } failure:^(NSString *code, NSString *msg) {
        Show_Msg_Error(msg)
    }];
}

@end
